package com.travel.travelServer.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Calendar;
import java.util.Date;

public class JWTUtils {

    //密钥
    public static String SECRET = "zhangqingshan";
    //Authorization
    private String header;

    //创建token
    //传入userid
    public static String createToken(String userId){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,24*60*60*7);
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256,SECRET);
        return builder.compact();
    }

    //解析jwt
    public static Claims parseToken(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

    public static void main(String[] args) {
        String token = createToken("1234");
        System.out.println(token);
        Claims claims = parseToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0IiwiaWF0IjoxNjkwMTAxMDU0LCJleHAiOjE2OTA3MDU4NTN9.Fi4xgYQWlmv7WJIyjxF3uVeL7JQGw94zoL1nl9R5WxI");
        System.out.println(claims);
    }

    //判断token是否过期
    public boolean judgeTokenExpiration(Date expiration){
        return expiration.before(new Date());
    }
}
